<?php

namespace common\observer\task\WorkOrder;

use common\model\TaskWorkOrderUserModel;
use common\model\UserModel;
use support\SingletonTrait;
use Throwable;
use teamones\dbeventObserver\interfaces\SplObserver;
use teamones\dbeventObserver\interfaces\SplSubject;

/**
 * 工单状态发生变化 通知工单群聊
 */
class StatusChangeSendMessageToChat implements SplObserver
{
    use SingletonTrait;

    public function update(SplSubject $subject): void
    {

        $updateData = $subject->getSplUpdateData();
        if (!isset($updateData['status'])) {
            return;
        }
        $taskWorkOrder = $subject->getSubjectData();
        if (empty($taskWorkOrder['chat_global_id'])) {
            return;
        }
        // 状态变更发送消息
        $workOrderUserList = model(TaskWorkOrderUserModel::class)
            ->field('user_id')
            ->where(['work_order_id' => $taskWorkOrder['id']])
            ->select();
        $saasUserIds = array_column($workOrderUserList, 'user_id');
        $imUserList = model(UserModel::class)->field('union_id')->where(['id' => ['IN', $saasUserIds]])->select();
        $imUserIds = array_column($imUserList, 'union_id');
        if (count($imUserIds) < 2) { // 防止群里只剩下一个人的时候,同时有人变更状态
            return;
        }
        try {
            $requestData = [
                "data" => [
                    'receives' => $imUserIds,
                    'content_type' => 'change_work_order_chat_status',
                    'global_id' => $taskWorkOrder['chat_global_id'],
                    'content_extra_data' => ['status' => $updateData['status']],
                ]
            ];
            teamones_request('teamones-im', 'message/push_work_order_chat_message', $requestData);
        } catch (Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
    }
}
